/*
 * DogeLoginFrame.java
 *
 * Created on 15 luglio 2007, 13.02
 */

package dogeUI;

import dogeCore.*;
import java.sql.SQLException;

/**
 *
 * @author  daniele
 */
public class DogeLoginFrame extends javax.swing.JPanel {
    
    /**
     * Creates new form DogeLoginFrame
     */
    public DogeLoginFrame(DogeCore core,DogeMainWindow ui) {
        this.ui=ui;
        this.core=core;
        initComponents();
        hideNotify();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        loginPanel = new javax.swing.JPanel();
        loginButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        usernameLabel = new javax.swing.JLabel();
        usernameField = new javax.swing.JTextField();
        passwordLabel = new javax.swing.JLabel();
        passwordField = new javax.swing.JPasswordField();
        bottomPanel = new javax.swing.JPanel();
        exitButton = new javax.swing.JButton();
        notifyLabel = new javax.swing.JLabel();

        setLayout(new java.awt.BorderLayout());

        setBorder(javax.swing.BorderFactory.createEtchedBorder());
        loginPanel.setLayout(new java.awt.GridBagLayout());

        loginPanel.setFocusable(false);
        loginButton.setFont(new java.awt.Font("Dialog", 1, 20));
        loginButton.setText("Login");
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(20, 0, 0, 0);
        loginPanel.add(loginButton, gridBagConstraints);

        jLabel1.setFont(new java.awt.Font("Dialog", 1, 14));
        jLabel1.setText("Inserire nome utente e password");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        loginPanel.add(jLabel1, gridBagConstraints);

        usernameLabel.setFont(new java.awt.Font("Dialog", 1, 14));
        usernameLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        usernameLabel.setLabelFor(usernameField);
        usernameLabel.setText("Nome utente:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(15, 0, 5, 0);
        loginPanel.add(usernameLabel, gridBagConstraints);

        usernameField.setFont(new java.awt.Font("Dialog", 0, 14));
        usernameField.setMinimumSize(new java.awt.Dimension(200, 19));
        usernameField.setPreferredSize(new java.awt.Dimension(200, 25));
        usernameField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                usernameFieldKeyTyped(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(15, 7, 5, 0);
        loginPanel.add(usernameField, gridBagConstraints);

        passwordLabel.setFont(new java.awt.Font("Dialog", 1, 14));
        passwordLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        passwordLabel.setLabelFor(passwordField);
        passwordLabel.setText("Password:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0);
        loginPanel.add(passwordLabel, gridBagConstraints);

        passwordField.setFont(new java.awt.Font("Dialog", 0, 14));
        passwordField.setMinimumSize(new java.awt.Dimension(200, 19));
        passwordField.setPreferredSize(new java.awt.Dimension(200, 25));
        passwordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                passwordFieldKeyTyped(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(10, 7, 11, 0);
        loginPanel.add(passwordField, gridBagConstraints);

        add(loginPanel, java.awt.BorderLayout.CENTER);

        bottomPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        exitButton.setFont(new java.awt.Font("Dialog", 1, 14));
        exitButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dogeUI/images/exit.gif")));
        exitButton.setText("Chiudi DoGe");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        bottomPanel.add(exitButton);

        add(bottomPanel, java.awt.BorderLayout.SOUTH);

        notifyLabel.setBackground(new java.awt.Color(238, 0, 0));
        notifyLabel.setFont(new java.awt.Font("Dialog", 1, 18));
        notifyLabel.setForeground(new java.awt.Color(255, 255, 255));
        notifyLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dogeUI/images/messagebox_critical.gif")));
        notifyLabel.setText("<html>Impossibile accedere: nome utente o password non validi. Verificare di averli digitati correttamente e che non sia attivo il tasto di blocco maiuscole</html>");
        notifyLabel.setToolTipText(notifyLabel.getText());
        notifyLabel.setFocusable(false);
        notifyLabel.setOpaque(true);
        add(notifyLabel, java.awt.BorderLayout.NORTH);

    }// </editor-fold>//GEN-END:initComponents

    private void passwordFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordFieldKeyTyped
        //filters the ENTER key, otherwise notification would not show when loginButton is activated with enter key
        if (evt.getKeyChar()!='\n'){
            hideNotify();
        }
    }//GEN-LAST:event_passwordFieldKeyTyped

    private void usernameFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_usernameFieldKeyTyped
        //filters the ENTER key, otherwise notification would not show when loginButton is activated with enter key
        if (evt.getKeyChar()!='\n'){
            hideNotify();
        }
    }//GEN-LAST:event_usernameFieldKeyTyped

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        terminateDoge();
    }//GEN-LAST:event_exitButtonActionPerformed
    
    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
        doLogin();
    }//GEN-LAST:event_loginButtonActionPerformed
    
    /**
     * Asks DogeCore to authenticate credentials
     */
    private void doLogin() {
        try {
            //ask to log in
            core.doLogin(usernameField.getText(), passwordField.getPassword());
            //login is successful, so load next form
            ui.loginSuccessful();
        } catch (SQLException ex) {
            //if SQLState is "28000" (bad credentials)...
            if (ex.getSQLState().equals("28000")){
                //...shows bad login notification and resets form
                usernameField.setText("");
                passwordField.setText("");
                notifyLabel.setVisible(true);
                usernameField.grabFocus();
            } else if (ex.getSQLState().equals("08S01")){
                //if SQLState is "08S01" (connection refused)
                javax.swing.JOptionPane.showMessageDialog(this,"La connessione al database è stata rifiutata.\nIl server del database non è raggiungibile o non si dispongono delle autorizzazioni di rete necessarie.\nContattare l'amministratore di sistema.","Errore nell'accesso alla base di dati",javax.swing.JOptionPane.ERROR_MESSAGE);
            } else {
                //show error dialog
                javax.swing.JOptionPane.showMessageDialog(this,"Si è verificato un errore accedendo al database.\nContattare l'amministratore di sistema.\n\nIl dettaglio dell'errore è:\n"+ex.getLocalizedMessage(),"Errore nell'accesso alla base di dati",javax.swing.JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            //show error dialog
            javax.swing.JOptionPane.showMessageDialog(this,"Si è verificato un errore accedendo al database.\nContattare l'amministratore di sistema.\n\nIl dettaglio dell'errore è:\n"+ex.getLocalizedMessage(),"Errore nell'accesso alla base di dati",javax.swing.JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * Exits from DoGe
     */
    private void terminateDoge() {
        //call terminateDoge in the main window, who will do the operation
        ui.terminateDoge();
    }

    /** hide notification area */
    private void hideNotify() {
        notifyLabel.setVisible(false);
    }
    
    /** returns the default button for this panel */
    protected javax.swing.JButton getDefaultButton(){
        return loginButton;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel bottomPanel;
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton loginButton;
    private javax.swing.JPanel loginPanel;
    private javax.swing.JLabel notifyLabel;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JTextField usernameField;
    private javax.swing.JLabel usernameLabel;
    // End of variables declaration//GEN-END:variables
    private DogeMainWindow ui;
    private DogeCore core;
}
